/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */



package org.ank.food;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class ProductPictureActivity extends Activity implements Runnable{
	public final static String INTENT_EXTRA_NAME = "prodpictact";
	private final static String PREFS_MODE = "prefmode";
	private final static String BUNDLE_KEY_IMAGE = "imagekey";
	private final static String BUNDLE_KEY_IMAGE_ARRAY = "imagearraykey";
//	private final static String BUNDLE_KEY_AMOUNT = "amountkey";
	private final static int MODE_SHOW_THUMBNAILS = 0;
	private final static int MODE_SHOW_IMAGE = 1;
	private final static int MESSAGE_SEARCH_STARTED = 0;
	private final static int MESSAGE_SEARCH_SUCCEEDED = 1;
	private final static int MESSAGE_SEARCH_FAILED = 2;
	private final static int DIALOG_PENDING = 0;
	
	private Button backButton, retryButton;
	private int mode, prodId;
	private GridView grid;
	private ImageView image;
	private ArrayList<BitmapDrawable> productDrawables;
	private ImageSearchHandler handler;
	private TextView productNameView, noInetView;
		
	@SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_picture_activity);
        
        grid = (GridView)findViewById(R.id.product_picture_grid);
        image = (ImageView)findViewById(R.id.product_picture_imageview);
        backButton = (Button)findViewById(R.id.product_picture_back_button);
        productNameView = (TextView)findViewById(R.id.product_picture_product_name);
        noInetView = (TextView)findViewById(R.id.product_picture_no_inet_text);
        retryButton = (Button)findViewById(R.id.product_picture_retry_button);

        mode = getPreferences(0).getInt(PREFS_MODE, MODE_SHOW_THUMBNAILS);
      
        if(mode == MODE_SHOW_IMAGE){
        	image.setVisibility(View.VISIBLE);
			grid.setVisibility(View.INVISIBLE);
		}else{
			image.setVisibility(View.INVISIBLE);
			grid.setVisibility(View.VISIBLE);
		}
        
        Intent parentIntent = getIntent();
        prodId = parentIntent.getIntExtra(INTENT_EXTRA_NAME, -1);

        setTitle(R.string.images_search);
        
        productNameView.setText( ProductDataManager.getInstance(getApplicationContext()).
    			getProductNameById(prodId) );
        
        backButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View arg0) {
				if(mode == MODE_SHOW_IMAGE){
					mode = MODE_SHOW_THUMBNAILS;
					image.setVisibility(View.INVISIBLE);
					grid.setVisibility(View.VISIBLE);
				}else{
					SharedPreferences.Editor editor = getPreferences(0).edit();
					editor.remove(PREFS_MODE);
					editor.commit();
					finish();
				}
			}
        });
        
        retryButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View arg0) {
				findAndSetImages();
			}
        });
        grid.setOnItemClickListener(new GridView.OnItemClickListener(){
			public void onItemClick(AdapterView<?> arg0, View view, int pos,
					long arg3) {
				image.setImageDrawable( ((ImageView)view).getDrawable() );
				mode = MODE_SHOW_IMAGE;
				grid.setVisibility(View.INVISIBLE);
				image.setVisibility(View.VISIBLE);
			}
        });
        handler = new ImageSearchHandler();
        if (   savedInstanceState != null && savedInstanceState.containsKey( BUNDLE_KEY_IMAGE_ARRAY )   ){
        	try{
        		productDrawables = 
        				(ArrayList<BitmapDrawable>)savedInstanceState
        						.getSerializable(BUNDLE_KEY_IMAGE_ARRAY);
        	}catch (ClassCastException e) {
				e.printStackTrace();
			}
        	Message m = Message.obtain(handler, MESSAGE_SEARCH_STARTED);
        	m.sendToTarget();
        	m = Message.obtain(handler, MESSAGE_SEARCH_SUCCEEDED);
        	m.sendToTarget();
        	if(mode == MODE_SHOW_IMAGE){
        		Bitmap bitmap;
        		if( (bitmap = (Bitmap)savedInstanceState.getParcelable(BUNDLE_KEY_IMAGE)) != null)
        			image.setImageBitmap(bitmap);
        	}
        }else
        	findAndSetImages();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		SharedPreferences.Editor editor = getPreferences(0).edit();
		editor.putInt(PREFS_MODE, mode);
		editor.commit();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		mode = getPreferences(0).getInt(PREFS_MODE, MODE_SHOW_THUMBNAILS);
	}
	
	@Override
	protected void onSaveInstanceState (Bundle outState){
		super.onSaveInstanceState(outState);
//		Log.v("onSaveIns", "start");
		if (productDrawables != null){
			outState.putSerializable(BUNDLE_KEY_IMAGE_ARRAY, productDrawables);
			if(mode == MODE_SHOW_IMAGE)
				outState.putParcelable(BUNDLE_KEY_IMAGE, 
						( (BitmapDrawable)image.getDrawable() ).getBitmap());
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			backButton.performClick();
			return true;
		}
	    return super.onKeyDown(keyCode, event);
	}
	
	public Dialog onCreateDialog(int code){
		ProgressDialog dialog = new ProgressDialog(this);
		switch(code){
		case DIALOG_PENDING:
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setMessage(getString(R.string.pending));
			return dialog;
		}
		return null;
	}
	
	private void findAndSetImages(){
		Thread t = new Thread(this);
        t.start();
	}
	
	public void run(){
		Message m = Message.obtain(handler, MESSAGE_SEARCH_STARTED);
		m.sendToTarget();
		//Log.v("pictures", " before getting drawables");
		if ( (productDrawables = InetManager.getInstance(getApplicationContext()).
				getProductDrawables(prodId)) == null){
			m = Message.obtain(handler, MESSAGE_SEARCH_FAILED);
			m.sendToTarget();
			return;
		}
		
		//Log.v("pictures", " after getting drawables");
		m = Message.obtain(handler, MESSAGE_SEARCH_SUCCEEDED);
		m.sendToTarget();
	}
	
	
	private class ImageSearchHandler extends Handler{
		public void handleMessage(Message m){
            switch (m.what){
            case MESSAGE_SEARCH_STARTED:
            	//Log.v("pictures handler", "recieved start");
            	backButton.setEnabled(false);
            	retryButton.setVisibility(View.GONE);
            	noInetView.setVisibility(View.GONE);
            	showDialog(DIALOG_PENDING);
            	break;
            case MESSAGE_SEARCH_SUCCEEDED:
            	//Log.v("pictures handler", "recieved success");
            	backButton.setEnabled(true);
            	grid.setAdapter(new ImageAdapter(getApplicationContext(), productDrawables));
            	dismissDialog(DIALOG_PENDING);
            	break;
            case MESSAGE_SEARCH_FAILED:
            	//Log.v("pictures handler", "recieved fail");
            	backButton.setEnabled(true);
//            	grid.setVisibility(View.GONE);
            	dismissDialog(DIALOG_PENDING);
            	retryButton.setVisibility(View.VISIBLE);
            	noInetView.setVisibility(View.VISIBLE);
            	break;
            }
		}
	}
	
	private class ImageAdapter extends BaseAdapter{
		
		private ArrayList<BitmapDrawable> content;
		private Context context;
		
		public ImageAdapter(Context c, ArrayList<BitmapDrawable> a){
			super();
			this.content = a;
			this.context = c;
		}
		
		public int getCount() {
			return content.size();
		}

		public Object getItem(int location) {
			return content.get(location);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(120, 120));
                imageView.setAdjustViewBounds(false);
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                imageView.setPadding(2, 2, 2, 2);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageDrawable(content.get(position));
            return imageView;
		}
	}
}
